//
//  LGPatientCarePlanController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/9/18.
//  照护计划

#import "LGPatientCarePlanController.h"
//模版导入
#import "LGPatientCareTemplateController.h"
//模版导入 - 介入治疗 、 药物治疗
#import "LGCareTemplateImportController.h"
#import "LGLungFollowSendController.h"//市一慢阻肺
//全年体征监测
#import "LGMonitoringSettingController.h"
//新增、编辑任务
#import "LGPatientCarePlanAddController.h"
//更新入院进展
#import "LGMedicineBallPlanController.h"
//发送短信提醒
#import "LGMedicineBallSMSController.h"
//模版导入弹框
#import "LGCareSelectTemplateView.h"
#import "LGCarePlanMonitorCell.h"
#import "LGCarePlanReviewCell.h"
#import "LGCarePlanCommonCell.h"
#import "LGBottomAlertView.h"
#import "DatePickerView.h"
@interface LGPatientCarePlanController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UIButton *sendBtn;
/**   */
@property (nonatomic , strong)UIButton *dateButton;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *tipView;
/**   */
@property (nonatomic , copy)NSString *currentDate;
/**  全年监测 */
@property (nonatomic , strong)NSArray *monitorArray;
/**  任务 */
@property (nonatomic , strong)NSArray *taskArray;
/**   */
@property (nonatomic , assign)BOOL canEdit;
/**   */
@property (nonatomic , copy)NSString *planid;
/**   */
@property (nonatomic , copy)NSString *currentPlan;
/**   */
@property (nonatomic , copy)NSString *smsContent;
@end

@implementation LGPatientCarePlanController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.planid = @"";
    self.canEdit = YES;
    self.currentDate = @"";
    self.currentPlan = @"";
    self.navigationView.title = @"查看照护计划";
    self.navigationView.rightBtn.titleLabel.font = LGFontWeight(15, UIFontWeightSemibold);
    [self.navigationView.rightBtn setTitle:@"发送提醒" forState:UIControlStateNormal];
    [self.navigationView.rightBtn setTitleColor:[UIColor colorWithString:@"#5E8EF5"] forState:UIControlStateNormal];
    [self.navigationView.rightBtn addTarget:self action:@selector(sendSmsAlerts) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.dateButton];
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, topBarHeight+viewPix(40), Screen_W, Screen_H-topBarHeight-viewPix(40)-viewPix(64)-bottomSafeBarHeight/4.0);
    [self createBottomView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
    [self requestCurrentPlan];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.care_plan/adjustCarePlanDetail" parameters:@{@"patient_id":self.patientid,@"searchdate":self.currentDate,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.planid = LGNSString(returnData[@"patient_careplan_id"]);
            self.smsContent = LGNSString(returnData[@"sms_content"]);
            self.currentDate = LGNSString(returnData[@"searchTime"]);
            [self.dateButton setTitle:[NSString stringWithFormat:@"查看范围 %@ 起",returnData[@"searchTime"]] forState:UIControlStateNormal];
            [self.dateButton setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:5];
            
            self.monitorArray = returnData[@"patient_tz"];
            self.taskArray = returnData[@"plan_task"];
            NSInteger confirmNum = [returnData[@"confirm_num"] integerValue];
            CGFloat height = (confirmNum>0)?viewPix(27):0.01;
            NSString *tipContent = [NSString stringWithFormat:@"待确认任务数量：%ld",confirmNum];
            [self.tipView setTitle:tipContent forState:UIControlStateNormal];
            self.tipView.frame = CGRectMake(0, 0, Screen_W, height);
            self.tableView.tableHeaderView = self.tipView;
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
            
    }];
}

-(void)requestCurrentPlan{
    [RequestUtil withPOST:@"/doctor/Careplan/fcInCarePlan" parameters:@{@"patient_id":self.patientid,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.currentPlan = LGNSString(returnData[@"applytype"]);
        }
    } error:^(NSError *error) {
        
    }];
}

//发送提醒
-(void)sendSmsAlerts{
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"短信预览" content:self.smsContent sureAction:^{
        [RequestUtil withPOST:@"/doctor/Careplan/sendcareMsg" parameters:@{@"patient_id":weakSelf.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [TooltipView showMessage:@"发送成功" offset:0];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            
        }];
    }];
}

//选择时间范围
-(void)selectDateRangeAction{
    DatePickerView *pickerView = [[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.currentDate = self.currentDate;
    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectDate = ^(NSString *date) {
        weakSelf.currentDate = date;
        [weakSelf.dateButton setTitle:[NSString stringWithFormat:@"查看范围 %@ 起",date] forState:UIControlStateNormal];
        [weakSelf.dateButton setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:5];
        [weakSelf requestData];
    };
}

//导入模版 -- 介入治疗、药物治疗
-(void)importTemplateAction{
    LGLungFollowSendController *controller = [[LGLungFollowSendController alloc]init];
    controller.patientid = self.patientid;
    controller.levelid = self.levelid;
    [self.navigationController pushViewController:controller animated:YES];
    
    return;
    if ([[NSObject appType:self.diseaseCode] isEqualToString:@"HX"]) {
        //华小芯、心康管家
        LGPatientCareTemplateController *controller = [[LGPatientCareTemplateController alloc]init];
        controller.patientid = self.patientid;
        [self.navigationController pushViewController:controller animated:YES];
        
    }else{
        //房颤
        [RequestUtil withPOST:@"/doctor/Careplan/fcInCarePlan" parameters:@{@"patient_id":self.patientid,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                self.currentPlan = LGNSString(returnData[@"applytype"]);
                LGCareSelectTemplateView *templateView = [[LGCareSelectTemplateView alloc]initWithTitle:@"选择康复计划模板" baseHeight:viewPix(315)+bottomSafeBarHeight/4.0];
                templateView.currentType = self.currentPlan;
                [[ObjectTool mainWindow] addSubview:templateView];
                [templateView showViewAnimation];
                __weak typeof(self) weakSelf = self;
                templateView.importTemplateType = ^(NSString * _Nonnull type) {
                    LGCareTemplateImportController *controller = [[LGCareTemplateImportController alloc]init];
                    controller.patientid = weakSelf.patientid;
                    controller.type = type;
                    [self.navigationController pushViewController:controller animated:YES];
                };
            }
        } error:^(NSError *error) {
            
        }];
    }
    
}

//新增任务
-(void)addTaskButtonAction{
    LGPatientCarePlanAddController *controller = [[LGPatientCarePlanAddController alloc]init];
    controller.patientid = self.patientid;
    controller.levelid = self.levelid;
    controller.taskid = @"0";
    [self.navigationController pushViewController:controller animated:YES];
}

//编辑全年体征监测
-(void)editMonitoringAction{
    LGMonitoringSettingController *controller = [[LGMonitoringSettingController alloc]init];
    controller.patientid = self.patientid;
    controller.planid = self.planid;
    [self.navigationController pushViewController:controller animated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.monitorArray.count;
    }else{
        return self.taskArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        LGCarePlanMonitorCell *monitorCell = [tableView dequeueReusableCellWithIdentifier:@"MonitorCell" forIndexPath:indexPath];
        monitorCell.selectionStyle = UITableViewCellSelectionStyleNone;
        monitorCell.dataDic = self.monitorArray[indexPath.row];
        return monitorCell;
    }else{
        NSDictionary *tempDic = self.taskArray[indexPath.row];
        NSString *type = LGNSString(tempDic[@"task_type"]);
        if([type isEqualToString:@"1"]){
            //复诊复查
            LGCarePlanReviewCell *reviewCell = [tableView dequeueReusableCellWithIdentifier:@"ReviewCell" forIndexPath:indexPath];
            reviewCell.selectionStyle = UITableViewCellSelectionStyleNone;
            reviewCell.dataDic = tempDic;
            return reviewCell;
        }else{
            //其他类型
            LGCarePlanCommonCell *commonCell = [tableView dequeueReusableCellWithIdentifier:@"CommonCell" forIndexPath:indexPath];
            commonCell.selectionStyle = UITableViewCellSelectionStyleNone;
            commonCell.dataDic = tempDic;
            return commonCell;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        __block NSDictionary *tempDic = self.taskArray[indexPath.row];
        NSString *status = LGNSString(tempDic[@"task_status_admin"]);
        NSString *confirm = LGNSString(tempDic[@"task_status_confirm"]);
        if([status isEqualToString:@"4"]){
            //已完成--不可点击
            return;
        }
        NSString *type = LGNSString(tempDic[@"task_type"]);
        __weak typeof(self) weakSelf = self;
        if([type isEqualToString:@"1"]||[type isEqualToString:@"5"] || [confirm isEqualToString:@"0"]){
            if(self.canEdit == YES){
                LGBottomAlertView *alertView = [[LGBottomAlertView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
                alertView.titleArray = @[@"标记完成",@"编辑任务"];
                [[UIApplication sharedApplication].keyWindow addSubview:alertView];
                alertView.itemButtonTouched = ^(NSInteger index) {
                    if (index == 0) {
                        //标记完成
                        [RequestUtil withPOST:@"/doctor/patient.care_plan/careplanTasksFinish" parameters:@{@"task_id":LGNSString(tempDic[@"task_id"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                            if(code == 200){
                                [weakSelf requestData];
                            }else{
                                [TooltipView showMessage:message offset:0];
                            }
                        } error:^(NSError *error) {
                            
                        }];
                    }else{
                        //编辑任务
                        LGPatientCarePlanAddController *controller = [[LGPatientCarePlanAddController alloc]init];
                        controller.taskSource = LGNSString(tempDic[@"task_source"]);
                        controller.taskid = LGNSString(tempDic[@"task_id"]);
                        controller.patientid = weakSelf.patientid;
                        controller.levelid = weakSelf.levelid;
                        [weakSelf.navigationController pushViewController:controller animated:YES];
                    }
                };
            }
        }else{
            LGBottomAlertView *alertView = [[LGBottomAlertView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
//            alertView.titleArray = (self.canEdit == YES)?@[@"发送短信提醒",@"标记完成",@"编辑任务"]:@[@"发送短信提醒"];//护士、康复医生不可编辑
            alertView.titleArray = @[@"标记完成",@"编辑任务"];
            [[ObjectTool mainWindow] addSubview:alertView];
            alertView.itemButtonTouched = ^(NSInteger index) {
                if (index == 0){
                    //标记完成
                    [RequestUtil withPOST:@"/doctor/patient.care_plan/careplanTasksFinish" parameters:@{@"task_id":LGNSString(tempDic[@"task_id"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                        if(code == 200){
                            [weakSelf requestData];
                        }else{
                            [TooltipView showMessage:message offset:0];
                        }
                    } error:^(NSError *error) {
                        
                    }];
                    
                }else{
                    //编辑任务
                    LGPatientCarePlanAddController *controller = [[LGPatientCarePlanAddController alloc]init];
                    controller.taskSource = @"";
                    controller.taskid = LGNSString(tempDic[@"task_id"]);
                    controller.patientid = weakSelf.patientid;
                    controller.levelid = weakSelf.levelid;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                }
            };
            /*
             if(index == 0){
                 //发送短信提醒
                 LGMedicineBallSMSController *controller = [[LGMedicineBallSMSController alloc]init];
                 controller.planids = LGNSString(tempDic[@"plan_id"]);
                 [weakSelf.navigationController pushViewController:controller animated:YES];
                 
             }else if (index == 1){
                 //更新入院进展
                 LGMedicineBallPlanController *controller = [[LGMedicineBallPlanController alloc]init];
                 controller.planids = LGNSString(tempDic[@"plan_id"]);
                 [weakSelf.navigationController pushViewController:controller animated:YES];
                 
             }
             */
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return (section == 0)?viewPix(56):0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = (section == 0)?viewPix(56):0.01;
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    headView.topMargin = viewPix(8);
    if (section == 0) {
        UIImageView *iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"照护计划-体征监测"]];
        iconView.frame = CGRectMake(viewPix(12), viewPix(12), viewPix(24), viewPix(24));
        [headView.shadowView addSubview:iconView];
        
        UILabel *typeLabel = [UILabel lableWithText:@"全年体征监测" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        typeLabel.frame = CGRectMake(viewPix(42), viewPix(12), viewPix(150), viewPix(24));
        [headView.shadowView addSubview:typeLabel];
         
        UIButton *actionBtn = [UIButton buttonWithTitle:@"编辑" titleFont:LGFont(13) textColor:@"#999999" imageName:@"grayTip12"];
        actionBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        actionBtn.frame = CGRectMake(0, 0, Screen_W-viewPix(44), viewPix(48));
        [actionBtn setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:3];
        [actionBtn addTarget:self action:@selector(editMonitoringAction) forControlEvents:UIControlEventTouchUpInside];
        [headView.shadowView addSubview:actionBtn];

        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(12), viewPix(48), Screen_W-viewPix(56), 0.5)];
        lineView.backgroundColor = [UIColor colorWithString:@"#E8E8E8"];
        [headView.shadowView addSubview:lineView];
        lineView.hidden = (self.monitorArray.count>0)?NO:YES;
        
    }
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return (section == 0)?viewPix(15):0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = (section == 0)?viewPix(15):0.01;
    LGCornerFooterView *footerView = [[LGCornerFooterView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    footerView.bottomMargin = viewPix(8);
    return footerView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight+viewPix(40), Screen_W, Screen_H-topBarHeight-viewPix(40)) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGCarePlanMonitorCell class] forCellReuseIdentifier:@"MonitorCell"];
        [_tableView registerClass:[LGCarePlanReviewCell class] forCellReuseIdentifier:@"ReviewCell"];
        [_tableView registerClass:[LGCarePlanCommonCell class] forCellReuseIdentifier:@"CommonCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(UIButton *)dateButton{
    if(!_dateButton){
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSString *content = [NSString stringWithFormat:@"查看范围 %@ 起",[formatter stringFromDate:[NSDate date]]];
        _dateButton = [UIButton buttonWithTitle:content titleFont:LGFont(15) textColor:@"#333333" imageName:@"grayTipDown2"];
        _dateButton.frame = CGRectMake(viewPix(20), topBarHeight+viewPix(12), Screen_W, viewPix(20));
        _dateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _dateButton.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(20), 0, 0);
        [_dateButton setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:5];
        [_dateButton addTarget:self action:@selector(selectDateRangeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dateButton;
}

-(UIButton *)tipView{
    if(!_tipView){
        _tipView = [UIButton buttonWithTitle:@"待确认任务数量：" titleFont:LGFont(15) textColor:@"#E53C39" imageName:@"照护计划-惊叹号"];
        _tipView.frame = CGRectMake(0, 0, Screen_W, viewPix(27));
        _tipView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _tipView.imageEdgeInsets = UIEdgeInsetsMake(0, viewPix(23), 0, 0);
        _tipView.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(25), 0, 0);
        _tipView.backgroundColor = [UIColor colorWithString:@"#FFE1E1"];
        _tipView.clipsToBounds = YES;
    }
    return _tipView;
}

-(void)createBottomView{
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, Screen_H-viewPix(64)-bottomSafeBarHeight/4.0, Screen_W, viewPix(64)+bottomSafeBarHeight/4.0)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    UIButton *importBtn = [UIButton buttonWithTitle:@"模版导入任务" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#429BFF" selectColor:@"#429BFF"];
    importBtn.frame = CGRectMake(viewPix(20), viewPix(8), (Screen_W-viewPix(60))/2.0, viewPix(45));
    importBtn.layer.borderColor = [UIColor colorWithString:@"#429BFF"].CGColor;
    importBtn.layer.borderWidth = 1;
    importBtn.cornerRidus = 10;
    [importBtn addTarget:self action:@selector(importTemplateAction) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:importBtn];
    
    UIButton *addButton = [UIButton buttonWithTitle:@"单个新增任务" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
    addButton.frame = CGRectMake(kMaxX(importBtn.frame)+viewPix(20), viewPix(8), (Screen_W-viewPix(60))/2.0, viewPix(45));
    addButton.backgroundColor = [UIColor colorWithString:@"#429BFF"];
    addButton.cornerRidus = 10;
    [addButton addTarget:self action:@selector(addTaskButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:addButton];
}


@end
